package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchService implements ISearchService {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 搜索栏自动补全功能
     *
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestion(String prefix) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "mysuggestion",
                    SuggestBuilders
                            .completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1 根据补全查询名称,获取补全结果suggestion
            CompletionSuggestion suggestion = suggest.getSuggestion("mysuggestion");

            // 获取options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            // 创建一个字符串集合来封装options数据
            List<String> list = new ArrayList<>(options.size());
            // 4.3 遍历
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }

           /* suggestion.getOptions().stream()
                    .map(CompletionSuggestion.Entry.Option::getText)
                    .map(Text::string)
                    .collect(Collectors.toList());*/
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * todo:过滤项聚合功能
     * 根据搜索条件搜索文档，并对文档中的分类、品牌做聚合，返回聚合得到的分类、品牌信息
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try {
            // 1.准备Reqyest
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1 query条件
            buildBasicQuery(params, request);
            // 2.2 设置size,只需要key,不需要文档数据
            request.source().size(0);

            // 2.3 聚合条件
            // 调用 聚合条件构建的方法
            buildAggregation(request);

            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            // 创建一个map用于接收聚合名称和聚合结果key
            Map<String, List<String>> result = new HashMap<>(2);
            Aggregations aggregations = response.getAggregations();
            // 调用 根据聚合名称获取聚合结果的方法
            // 4.1 根据品牌名称,获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            // 4.2 根据城市名称,获取城市结果
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryList);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 实现基本搜索功能(关键字搜索,分类,品牌,价格过滤,分页,排序,高亮显示)
     * 分页,排序,高亮
     * 根据搜索条件搜索文档
     * @param params
     * @return
     */
    @Override
    public PageDTO<ItemDoc> searchList(RequestParams params) {
        try {
            // 1.准备Reqyest
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1 query条件
            buildBasicQuery(params, request);
            // 2.2 分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            // 2.3 排序
            // 销量按降序排序,价格按升序排序
            String sortBy = params.getSortBy();
            if ("sold".equals(sortBy)) {
                request.source().sort(sortBy, SortOrder.DESC);
            } else if ("price".equals(sortBy)) {
                request.source().sort(sortBy, SortOrder.ASC);
            }
            // 2.4 高亮显示
            HighlightBuilder name = new HighlightBuilder().field("name").requireFieldMatch(false);
            request.source().highlighter(name);

            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            SearchHits searchHits = response.getHits();
            // 4.1 获取总条数
            long total = searchHits.getTotalHits().value;
            // 4.2 文档数据数组
            SearchHit[] hits = searchHits.getHits();
            List<ItemDoc> list = new ArrayList<>(hits.length);
            // 4.3 遍历
            for (SearchHit hit : hits) {
                // 4.4 获取source
                String json = hit.getSourceAsString();
                // 4.5 反序列化(转Java)
                ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
                // 4.6 获取高亮
                // 根据字段名获取高亮结果
                Map<String, HighlightField> map = hit.getHighlightFields();
                if (map != null && map.size() > 0) {
                    // 获取高亮值(map 通过key获取值: get)
                    HighlightField field = map.get("name");
                    String value = field.getFragments()[0].string();
                    // 覆盖非高亮结果
                    itemDoc.setName(value);
                }
                list.add(itemDoc);
            }
            // 封装返回对象
            PageDTO<ItemDoc> pageDTO = new PageDTO<>(total, list);
            return pageDTO;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 注入feign-api中的ItemClient
    @Autowired
    private ItemClient itemClient;
    /**
     * 监听商品新增上架
     * @param id
     */
    @Override
    public void saveItemById(Long id) {
        try {
            // 1.查询商品数据
            Item item = itemClient.queryById(id);
            ItemDoc itemDoc = new ItemDoc(item);
            // 2.准别Request
            IndexRequest request = new IndexRequest("item").id(id.toString());
            // 3.准备DSl
            // 序列化(转为json)
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 4.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 监听商品下架
     * @param id
     */
    @Override
    public void deleteItemById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("item", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * query查询条件(关键字搜索,品牌,分类,价格,竞价排名)
     * 关键字搜索,品牌,分类,价格,竞价排名
     * @param params
     * @param request
     */
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // A. 1.创建布尔查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.key 关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            // key为空
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            // key不为空
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 3.brand 品牌
        String brand = params.getBrand();
        if (brand != null && !brand.equals("")) {
            // brand 非空
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 4.category 分类
        String category = params.getCategory();
        if (category != null && !category.equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }
        // 5.price 价格
        Long minPrice = params.getMinPrice();
        Long maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice * 100).lte(maxPrice * 100));
        }

        // B. 6.算分控制 -竞价排名
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询,相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件(实现广告置顶)
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });

        // 7.放入source
        request.source().query(functionScoreQuery);
    }

    /**
     * 聚合条件构建的方法
     *
     * @param request
     */
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(20)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(20)
        );
    }

    /**
     * 根据聚合名称(品牌名称)获取聚合结果(品牌结果)的方法
     *
     * @param aggregations
     * @return
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1 根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2 获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3 遍历
        // 创建一个list集合用于接收key
        List<String> keyList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4 获取key
            String key = bucket.getKeyAsString();
            keyList.add(key);
        }
        return keyList;
    }
}
